package org.judking.CarKeeper.command.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.judking.CarKeeper.command.BaseObdCommand;
import org.judking.CarKeeper.command.VinObdCommand;
import org.judking.CarKeeper.command.bean.CommandBean;
import org.judking.CarKeeper.command.bean.CommandTransmitter;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import android.util.Log;

public class JsonLogger extends CommandListener {
	public static final String DELIM = "#DlM#";
	
	@Override
	public void run() {
		CommandTransmitter transmitter = genCmdTransmitter();
		GsonBuilder builder = new GsonBuilder();
		builder.excludeFieldsWithModifiers(Modifier.TRANSIENT);
		Gson gson = builder.create();
		String jsonStr = gson.toJson(transmitter);
		
		try {
			SynFileOpreService.synAppend(jsonStr+DELIM);
		} catch (IOException e) {
			Log.e("judking", "SynFileOpreService.synAppend IOException : "+e.getMessage());
		}		
	}
	
	private CommandTransmitter genCmdTransmitter()		{
		CommandTransmitter transmitter = new CommandTransmitter();
		List<CommandBean> list = new ArrayList<CommandBean>();
		for(BaseObdCommand command : commands)	{
			list.add(genCmdBean(command));
			if(command instanceof VinObdCommand)		{
				transmitter.setVin(command.getRipeData().toString()); 
			}
		}
		transmitter.setCommands(list);
		
		return transmitter;
	}

	private CommandBean genCmdBean(BaseObdCommand command) {
			CommandBean commandBean = new CommandBean();
			commandBean.setName(command.getName());
			commandBean.setCmd(command.genCmd());
			commandBean.setRipeData(command.getRipeData());
		return commandBean;
	}
	
	
	

}
